package generic.net.client;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import generic.net.Peer;

/**
 * Client Networking class.
 *
 * A Peer that initiates a connection to a server.
 *
 * @author Adam Scarr <scarr.adam@gmail.com>
 */
public class Client extends Peer {
    private int port;
    private String hostname;

    /**
     * Create a new client connection, that is not connected.
     *
     * You should call connect() manually.
     */
    public Client() {

    }

    /**
     * Create a new connection to the server.
     *
     * @param hostname  Servers hostname.
     * @param port      Servers port.
     */
    public Client(String hostname, int port) {
        connect(hostname, port);
    }

    /**
     * Establishes the connection to the server.
     */
    public void connect(String hostname, int port) {
        this.port = port;
        this.hostname = hostname;
        System.out.println("[CLIENT] Connecting...");

        try {
            connect(new Socket(hostname, port));
        } catch (UnknownHostException ex) {
            System.out.println("[CLIENT] Could not resolve host " + hostname);
            System.exit(0);
        } catch (IOException ex) {
            System.out.println("[CLIENT] Could not connect to port.");
            return;
        }
    }
}
